package cmp.database;

import java.sql.ResultSet;

import cmp.main.Globals;
import assem.DBConn;

import util.Debug.ErrorReport;

/***************************************************
 * If columns are being added for a version, add them here and to schema
 * NOTE: LoadPAVE adds the dynamic columns
 */
public class Version {

	public Version (DBConn mDB, String Sver) { 
		if (Sver.equals("v1.1")) addV11(mDB);
	}
	
	private void addV11(DBConn mDB) {
		try {
			if (!tableHasColumn(mDB, "assembly", "isPep"))
				mDB.executeUpdate("alter table assembly add isPep tinyint default 0");
			// if allPOGlib is null, then don't show RPKM in cluster, same with DE
			if (!tableHasColumn(mDB, "info", "hasLib")) {
				mDB.executeUpdate("alter table info add hasLib tinyint default 0");
				mDB.executeUpdate("alter table info add hasDE tinyint default 0");
				mDB.executeUpdate("alter table info add allSeqLib text");
				mDB.executeUpdate("alter table info add allPOGLib text");				
				mDB.executeUpdate("alter table info add allSeqDE text");
				mDB.executeUpdate("alter table info add allPOGDE text");
				mDB.executeUpdate("alter table info add allASM text");
				mDB.executeUpdate("alter table info add allMethods text");
				mDB.executeUpdate("alter table info add allTaxa text");	
			}
			if (!hasTable(mDB, "pairwise")) {

				mDB.executeUpdate("create table pairwise " +
						"(" +
						"PWID 		integer not null PRIMARY KEY AUTO_INCREMENT, " +
						"UTid1 		varchar(30) NOT NULL, " +
						"UTid2 		varchar(30) NOT NULL, " +
						"UTstr1 		VARCHAR(30) not null, " +
						"UTstr2 		VARCHAR(30) not null, " +
						"PCC				DOUBLE default 0, " + 
						"index idx1(UTid1), " +
						"index idx2(UTid2), " +
						"index idx3(PWid) " +
						") " 
						);
				mDB.executeUpdate("alter table pog_groups add LmaxPCC double default 0");
				mDB.executeUpdate("alter table pog_groups add LperPCC double default 0");
			}
		}
		catch (Exception e) {
			ErrorReport.die(e, "Error updating schema");
		}
	}
	
	public boolean hasTable(DBConn mDB, String name) throws Exception
	{
		ResultSet rs = mDB.executeQuery("show tables like '" + name + "'");
		boolean retVal = rs.first();
		rs.close();
		return retVal;
	}
	public boolean tableHasColumn(DBConn mDB, String table, String column) throws Exception
	{
		ResultSet rs = mDB.executeQuery("show columns from " + table + " where field='" + column + "'");
		boolean ret = rs.first();
		rs.close();
		return ret;
	}
}
